import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {Buffer} from "buffer";
import {RN} from "./RN";
import {MAC} from "./MAC";


export class RN_MAC implements AxdrType{

    dataCode : Buffer | null = null;
    rn : RN | null = null;
    mac : MAC | null = null;

    constructor() {
    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(rn : RN, mac : MAC){
        this.rn = rn;
        this.mac = mac;
    }

    setRn(rn : RN){
        this.rn = rn;
    }

    setMac(mac : MAC){
        this.mac = mac;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.rn = new RN();
        codeLength += this.rn.decode(input);

        this.mac = new MAC();
        codeLength += this.mac.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {

        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.rn != null && this.mac != null){
                codeLength = 0;
                codeLength += this.mac.encode(output);
                codeLength += this.rn.encode(output);
            }else{
                throw new Error("rn or mac is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.rn != null && this.mac != null) {
            "sequence: {"+ "rn: " + this.rn + ", mac: " + this.mac  + "}";
        } else {
            return "rn || mac is null";
        }
    }

}
